#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
import socket
import sys
import datetime
from paramiko.py3compat import u
from core.log_write import Log_wirite
try:
    import termios
    import tty
    has_termios = True
except ImportError:
    has_termios = False


def interactive_shell(chan, user_id, bindhost_use):
    if has_termios:  # 只支持Linux下的命令操作
        posix_shell(chan, user_id, bindhost_use)


def posix_shell(chan, user_id, bindhost_use):
    import select

    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)
        cmd = ''

        tab_key = False
        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = u(chan.recv(1024))
                    if tab_key:
                        if x not in ('\x07', '\r\n'):
                            cmd += x
                        tab_key = False
                    if len(x) == 0:
                        sys.stdout.write('\r\n*** EOF\r\n')
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if '\r' != x:  # 如果不是输入的回车，说明命令还没输入完毕，持续拼接命令
                    cmd += x
                else:  # 命令输入完毕
                    cmd_input = cmd.replace("\t", "").strip()  # 将命令录入中输入的tab键剔除
                    date = datetime.datetime.now()
                    log_obj = Log_wirite(user_id, bindhost_use.id, cmd_input, date)  # 将用户操作命令录入数据库
                    log_obj.log_recording()
                    cmd = ''  # cmd变量情况，以存放下次命令
                if '\t' == x:  # 捕捉tab
                    tab_key = True
                if len(x) == 0:
                    break
                chan.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)